<?php

namespace app\admin\model\wechat;

use think\Db;
use think\Model;
use app\admin\model\Admin;

class Accounts extends Model
{

    // 表名
    protected $name = 'wechat_accounts';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getAuths()
    {
        $auths = array(
            array("label"=> '否',"value"=>0),
            array("label"=> '是',"value"=>1),
        );
        return $auths;
    }

    public function getAccountTypes()
    {
        $auths = array(
            array("label"=> '个人',"value"=>'person'),
            array("label"=> '企业',"value"=>'company'),
        );
        return $auths;
    }

    public function getAccessToken(){
         $userinfo = \think\Session::get('admin');
         $uid = $userinfo['id'];

        $info = Db::name('admin')->where('id', $uid)->find();
        $appid = $info['appid'];
        $appsecret = $info['appsecret'];
        $url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
//echo $url_token;
        // 可能不在ip白名单
        // $rs = file_get_contents($url_token);
        // print_r($rs);
        // echo  $url_token;exit;
        $curl_info = curl_weixin($url_token);
//     print_r($curl_info);EXIT;

        $curl_token = json_decode($curl_info,true);

        if (!isset($curl_token['access_token'])) {
            echo json_encode(array("result" => "获取access_token失败，" . $curl_token['errmsg'], "code" => "fail"));
            exit;
        }

        $access_token = $curl_token['access_token'];
        return $access_token;
    }

}
